<?php

namespace App\Http\Controllers\Api;

use App\Models\Student;
use App\Http\Controllers\Controller;
use App\Http\Requests\ImportRequest;
use Illuminate\Http\Request;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;

class StudentImportController extends Controller
{
    public function import(ImportRequest $request)
    {

        if ($request->file('import_file')->getClientOriginalExtension() != 'xlsx'){
            return response()->json(['error' => '文件格式必须是xlsx']);
        }
        $IOFactory = IOFactory::createReader('Xlsx');
        $reader = $IOFactory->load(\request()->file('import_file'));
        $worksheet = $reader->getActiveSheet();
        $list = $worksheet->toArray();
        unset($list[0]);
        $start = 1;
        foreach ($worksheet->getDrawingCollection() as $drawing){

            if ($drawing instanceof Drawing){
                $filename = $drawing->getPath();
                $imageFilename = $drawing->getIndexedFilename();
                $path = '/images/'.md5(time()).$imageFilename;
                copy($filename, 'uploads'.$path);
                $list[$start][0] = $path;
            }
            $start ++;
        }
        $data = [];
        foreach ($list as $item){
            $student = array(
            'photo'=>$item[0],
            'name' => $item[1],
            'num'  => $item[2],
            'school_id' => $item[3],
            'sex'  => $item[4],
             'age' => $item[5]
        );
           array_push($data, $student);
        }
        $students = new Student();
        $students->addAll($data);
        return [];
    }
}
